#!/bin/bash

#定义变量
API_NAME="blog"
API_VERSION="3.2.1"
JENKINS_PRO_NAME="blog-maven-test"

#定义服务和对应端口
SERVER_NAME_ARR[0]="article"
SERVER_NAME_ARR[1]="data"
SERVER_NAME_ARR[2]="gateway"
SERVER_NAME_ARR[3]="third"
SERVER_NAME_ARR[4]="user"

SERVER_NAME_PORT_ARR[0]=8200
SERVER_NAME_PORT_ARR[1]=9200
SERVER_NAME_PORT_ARR[2]=8000
SERVER_NAME_PORT_ARR[3]=9100
SERVER_NAME_PORT_ARR[4]=8100


#复制Dockerfile
cd $WORKSPACE/

#循环服务操作 - 生成对应docker文件
#while循环遍历
i=0
while [[ i -lt ${#SERVER_NAME_ARR[@]} ]]; do

        MODULE_NAME=$API_NAME-${SERVER_NAME_ARR[i]}

        #添加镜像到服务中
        cp /var/jenkins_home/workspace/$JENKINS_PRO_NAME/blog-compile/docker/${SERVER_NAME_ARR[i]}/Dockerfile .

        #定义镜像名称
        IMAGE_NAME="192.168.0.101:5001/liyang/$MODULE_NAME:$BUILD_NUMBER"
        #构建Docker镜像
        docker build -t $IMAGE_NAME .

        #若存在原镜像的容器，删除
        CONTAINER_NAME=$MODULE_NAME-$API_VERSION
        cid=$(docker ps -a | grep "$CONTAINER_NAME" | awk '{print $1}')
        if [ "$cid" != "" ];then
            docker rm -f $cid
        fi

        #启动容器
        docker run -d -p ${SERVER_NAME_PORT_ARR[i]}:${SERVER_NAME_PORT_ARR[i]} --name $CONTAINER_NAME $IMAGE_NAME

        #删除Dockerfile文件
        rm -f  Dockerfile

    let i++
done

